package com.atguigu.flink.chapter03_exec1;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Smexy on 2022/10/24
 *     过滤出pageView,再根据userId去重
 *          215662
 */
public class Demo2_UV
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
            .readTextFile("data/UserBehavior.csv")
            //map + filter
            .flatMap(new FlatMapFunction<String, String>()
            {
                @Override
                public void flatMap(String value, Collector<String> out) throws Exception {
                    String[] words = value.split(",");
                    if ("pv".equals(words[3])){
                        out.collect(words[0]);
                    }
                }
            })
            //全局汇总
            .global()
            .process(new ProcessFunction<String, Long>()
            {
               //去重 HashSet
                Set<String> uids = new HashSet<>();
                @Override
                public void processElement(String uid, Context ctx, Collector<Long> out) throws Exception {

                    //元素之集合中不存在，添加成功，返回true
                    boolean ifExist = uids.add(uid);

                    if (ifExist) out.collect(uids.size() + 0l);

                }
            }).setParallelism(1)
            .print().setParallelism(1);

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
}
